﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cesave.Domain.PermisosModule.Entities;
using System.ComponentModel;
using Cesave.Domain.PermisosModule.Contracts.Juntas;
using Cesave.Infrastructure.CrossCutting.IoC;
using System.Windows.Forms;

namespace Cesave.DistributedServices.PermisosModule.WindowsHost.ViewModels.Catalogs.Modulos
{
	public partial class ModulosViewModel
	{
		#region Private methods

		/// <summary>
		/// 
		/// </summary>
		private List<Junta> _juntas;

		/// <summary>
		/// 
		/// </summary>
		private Junta _junta;

		#endregion

		#region Public properties

		/// <summary>
		/// 
		/// </summary>
		public List<Junta> Juntas
		{
			get
			{
				return _juntas;
			}
			private set
			{
				_juntas = value;
				if (_juntas != null)
					RaisePropertyChanged("Juntas");
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public Junta Junta
		{
			get
			{
				return _junta;
			}
			private set
			{
				_junta = value;
				if (_junta != null)
					RaisePropertyChanged("Junta");
			}
		}

		#endregion

		#region Private methods

		/// <summary>
		/// 
		/// </summary>
		private void LoadJuntas()
		{
			StartWaiting();
			using (BackgroundWorker worker = new BackgroundWorker())
			{
				worker.DoWork += (sender, e) =>
				{
					IJuntaService service = IoCFactory.Resolve<IJuntaService>();
					e.Result = service.FindJuntasByEstado(Estado.EstadoGuid);
				};
				worker.RunWorkerCompleted += (sender, e) =>
				{
					EndWaiting();
					if (!e.Cancelled && e.Error == null)
						Juntas = e.Result as List<Junta>;
					else if (e.Error != null)
						ShowMessage(e.Error.Message);
				};
				worker.WorkerSupportsCancellation = true;
				worker.RunWorkerAsync();
			}
		}

		#endregion

		#region Event methods

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void SetCurrentJunta(object sender, EventArgs e)
		{
			BindingSource bindingSource = sender as BindingSource;
			if ((bindingSource != null) && (bindingSource.Current != null))
				Junta = bindingSource.Current as Junta;
		}

		/// <summary>
		/// 
		/// </summary>
		private void OnJuntasPropertyChanged()
		{
			_view.juntasBindingSource.DataSource = Juntas;
			_view.juntasBindingSource.CurrentChanged += SetCurrentJunta;
			SetCurrentJunta(_view.juntasBindingSource, new EventArgs());
		}

		/// <summary>
		/// 
		/// </summary>
		private void OnJuntaPropertyChanged()
		{
			LoadModulos();
			if (IsModuloReady)
			{
				Modulo.JuntaGuid = Junta.JuntaGuid;
				Modulo.JuntaId = Junta.JuntaId;
			}
		}

		#endregion

	}
}
